import React, { useState, useEffect, useRef } from 'react';
import { 
  Container, 
  Grid, 
  CssBaseline, 
  Paper,
  Tabs,
  Tab,
  Box,
  Typography,
  Avatar,
  Divider,
  Button,
  TextField,
  List,
  ListItem,
  Card,
  CardContent,
  Chip,
  IconButton,
  Tooltip
} from '@mui/material';
import { Link, useLocation, useParams, useNavigate } from 'react-router-dom';
import Navbar from '../components/Navbar';
import ThumbUpIcon from '@mui/icons-material/ThumbUp';
import ChatBubbleOutlineIcon from '@mui/icons-material/ChatBubbleOutline';
import ShareIcon from '@mui/icons-material/Share';
import BookmarkBorderIcon from '@mui/icons-material/BookmarkBorder';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import PersonAddIcon from '@mui/icons-material/PersonAdd';
import PersonRemoveIcon from '@mui/icons-material/PersonRemove';
import { navigationItems } from '../App';


// 模拟帖子数据
const posts = [
  {
    id: 1,
    title: '求助：下载速度特别慢怎么解决？',
    content: '最近下载种子速度特别慢，有没有大佬能分享一下提速的经验？我的网络环境是100M宽带，但下载速度只有几十KB/s，感觉很不正常。已经尝试了更换tracker和调整连接数，但效果不明显。',
    author: '新手小白',
    avatar: 'https://i.pravatar.cc/150?img=1',
    date: '2024-05-01',
    likes: 12,
    comments: 8,
    tags: ['求助', '下载问题']
  },
  {
    id: 2,
    title: '分享：最近看了部超赞的电影！',
    content: '最近看了《沙丘2》，画面和剧情都非常震撼，强烈推荐给大家！\n\n导演丹尼·维伦纽瓦再次展现了他的才华，将弗兰克·赫伯特的小说完美地搬上了大银幕。电影中的视觉效果令人惊叹，音乐也非常配合剧情发展。\n\n特别喜欢保罗·亚崔迪斯的角色塑造，他的内心挣扎和成长历程非常有深度。\n\n有没有看过的朋友可以一起讨论交流？',
    author: '影视达人',
    avatar: 'https://i.pravatar.cc/150?img=2',
    date: '2024-04-30',
    likes: 45,
    comments: 23,
    tags: ['影视分享', '推荐']
  },
  {
    id: 3,
    title: '活动：五一假期种子分享大会',
    content: '五一假期来临，站内将举办种子分享活动，上传优质资源可获得额外积分奖励！\n\n活动时间：2024年5月1日至5月5日\n\n活动规则：\n1. 上传2024年新发布的高清影视资源，每个资源奖励100积分\n2. 上传冷门但有价值的学习资料，每个资源奖励200积分\n3. 上传原创音乐或视频作品，每个作品奖励500积分\n\n所有参与活动的用户还将有机会抽取杨桃奖励，最高可得1000杨桃！\n\n快来参与吧！',
    author: '站长小李',
    avatar: 'https://i.pravatar.cc/150?img=3',
    date: '2024-04-29',
    likes: 89,
    comments: 36,
    tags: ['官方活动', '积分奖励']
  },
  {
    id: 4,
    title: '讨论：大家都用什么下载软件？',
    content: '想了解下大家都用什么下载工具，qBittorrent和Transmission哪个更好用？我目前在Windows系统上使用qBittorrent，感觉还不错，但听说Transmission在占用资源方面更轻量。另外，有没有其他推荐的下载软件？使用体验如何？',
    author: '技术宅',
    avatar: 'https://i.pravatar.cc/150?img=4',
    date: '2024-04-28',
    likes: 32,
    comments: 47,
    tags: ['讨论', '下载工具']
  },
];

// 模拟评论数据
const postComments = {
  1: [
    {
      id: 1,
      author: '网络老手',
      avatar: 'https://i.pravatar.cc/150?img=10',
      content: '检查一下你的ISP是否进行了限速，有些运营商会对BT下载进行特殊处理。',
      date: '2024-05-01 10:30',
      likes: 5,
      replies: [
        {
          id: 1,
          author: '新手小白',
          avatar: 'https://i.pravatar.cc/150?img=1',
          content: '谢谢提醒，我会联系一下我的网络运营商。',
          date: '2024-05-01 11:15',
          likes: 2,
          replyToUser: '网络老手'
        }
      ]
    },
    {
      id: 2,
      author: '技术达人',
      avatar: 'https://i.pravatar.cc/150?img=11',
      content: '可以尝试一下使用VPN，有时候能解决这类问题。另外，建议检查一下你的客户端设置，特别是连接数和上传速度限制。',
      date: '2024-05-01 11:45',
      likes: 8,
      replies: []
    }
  ],
  2: [
    {
      id: 1,
      author: '电影爱好者',
      avatar: 'https://i.pravatar.cc/150?img=12',
      content: '完全同意！《沙丘2》的视觉效果太震撼了，IMAX版本更是值得一看。',
      date: '2024-04-30 15:20',
      likes: 12,
      replies: [
        {
          id: 1,
          author: '影视达人',
          avatar: 'https://i.pravatar.cc/150?img=2',
          content: '是的！我就是在IMAX看的，体验非常棒。',
          date: '2024-04-30 15:40',
          likes: 3,
          replyToUser: '电影爱好者'
        },
        {
          id: 2,
          author: '普通观众',
          avatar: 'https://i.pravatar.cc/150?img=22',
          content: '我只看过普通版本，下次一定要尝试IMAX。',
          date: '2024-04-30 16:10',
          likes: 1,
          replyToUser: '电影爱好者'
        }
      ]
    },
    {
      id: 2,
      author: '科幻迷',
      avatar: 'https://i.pravatar.cc/150?img=13',
      content: '作为原著粉丝，我觉得这部电影对原著的还原度非常高，同时又有自己的创新。',
      date: '2024-04-30 16:35',
      likes: 9,
      replies: []
    },
    {
      id: 3,
      author: '影评人',
      avatar: 'https://i.pravatar.cc/150?img=14',
      content: '丹尼·维伦纽瓦的导演功力真的不得不佩服，他对科幻世界的构建非常有一套。期待他未来的作品！',
      date: '2024-04-30 18:15',
      likes: 15,
      replies: []
    }
  ],
  3: [
    {
      id: 1,
      author: '资源控',
      avatar: 'https://i.pravatar.cc/150?img=15',
      content: '这个活动太棒了！已经准备好了几部2024年的新片，马上就上传。',
      date: '2024-04-29 09:10',
      likes: 6,
      replies: []
    },
    {
      id: 2,
      author: '学习狂',
      avatar: 'https://i.pravatar.cc/150?img=16',
      content: '我有一些很棒的学习资料，正好可以分享出来。请问冷门资料具体指什么类型呢？',
      date: '2024-04-29 10:25',
      likes: 4,
      replies: [
        {
          id: 1,
          author: '站长小李',
          avatar: 'https://i.pravatar.cc/150?img=3',
          content: '比如非主流学科、小众技术、稀有文献等，只要有学习价值都可以。',
          date: '2024-04-29 10:40',
          likes: 2,
          replyToUser: '学习狂'
        }
      ]
    }
  ],
  4: [
    {
      id: 1,
      author: 'Linux用户',
      avatar: 'https://i.pravatar.cc/150?img=17',
      content: '我在Linux系统上用Transmission，真的很轻量，而且稳定性不错。',
      date: '2024-04-28 14:05',
      likes: 10,
      replies: []
    },
    {
      id: 2,
      author: 'Mac爱好者',
      avatar: 'https://i.pravatar.cc/150?img=18',
      content: '作为Mac用户，我觉得Transmission的界面更符合macOS的设计风格，但功能上qBittorrent可能更强大一些。',
      date: '2024-04-28 15:30',
      likes: 7,
      replies: []
    },
    {
      id: 3,
      author: '资深用户',
      avatar: 'https://i.pravatar.cc/150?img=19',
      content: '推荐尝试一下Deluge，它结合了qBittorrent的功能性和Transmission的轻量，而且支持插件扩展。',
      date: '2024-04-28 16:40',
      likes: 12,
      replies: [
        {
          id: 1,
          author: '技术宅',
          avatar: 'https://i.pravatar.cc/150?img=4',
          content: '谢谢推荐，我会试试看Deluge。你用过哪些好用的插件吗？',
          date: '2024-04-28 17:15',
          likes: 3,
          replyToUser: '资深用户'
        },
        {
          id: 2,
          author: '新用户',
          avatar: 'https://i.pravatar.cc/150?img=25',
          content: 'Deluge对新手友好吗？配置复杂吗？',
          date: '2024-04-28 18:30',
          likes: 0,
          replyToUser: '资深用户'
        }
      ]
    }
  ]
};

function PostDetail() {
  const location = useLocation();
  const navigate = useNavigate();
  const { postId } = useParams();
  const [post, setPost] = useState(null);
  const [comments, setComments] = useState([]);
  const [commentText, setCommentText] = useState('');
  const [liked, setLiked] = useState(false);
  const [likedComments, setLikedComments] = useState({});
  const commentInputRef = useRef(null);
  // 添加关注状态
  const [following, setFollowing] = useState(false);
  // 添加回复状态
  const [replyTo, setReplyTo] = useState(null);
  const [replyText, setReplyText] = useState('');
  const [replyToInfo, setReplyToInfo] = useState(null);
  
  useEffect(() => {
    // 根据postId获取对应的帖子和评论
    const id = parseInt(postId);
    const foundPost = posts.find(p => p.id === id);
    if (foundPost) {
      const postCommentsList = postComments[id] || [];
      setPost({...foundPost, comments: postCommentsList.length}); // 更新帖子的评论数量为实际评论列表长度
      setComments(postCommentsList);
      // 重置点赞状态
      setLiked(false);
      setLikedComments({});
    }
  }, [postId]);
  
  // 处理评论区域跳转
  const scrollToCommentInput = () => {
    if (commentInputRef.current) {
      commentInputRef.current.focus();
      commentInputRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  };
  
  const handleLike = () => {
    if (!liked && post) {
      setPost({...post, likes: post.likes + 1});
      setLiked(true);
    } else if (liked && post) {
      setPost({...post, likes: post.likes - 1});
      setLiked(false);
    }
  };
  
  const handleCommentSubmit = () => {
    if (commentText.trim()) {
      const newComment = {
        id: comments.length + 1,
        author: '当前用户',
        avatar: 'https://i.pravatar.cc/150?img=20',
        content: commentText,
        date: new Date().toLocaleString(),
        likes: 0
      };
      
      const updatedComments = [...comments, newComment];
      setComments(updatedComments);
      setCommentText('');
      
      if (post) {
        setPost({...post, comments: updatedComments.length}); // 更新帖子的评论数量为评论列表长度
      }
    }
  };
  
  const handleCommentLike = (commentId) => {
    const updatedComments = comments.map(comment => {
      if (comment.id === commentId) {
        // 检查该评论是否已点赞
        if (likedComments[commentId]) {
          // 已点赞，取消点赞
          setLikedComments(prev => ({...prev, [commentId]: false}));
          return {...comment, likes: comment.likes - 1};
        } else {
          // 未点赞，添加点赞
          setLikedComments(prev => ({...prev, [commentId]: true}));
          return {...comment, likes: comment.likes + 1};
        }
      }
      return comment;
    });
    
    setComments(updatedComments);
  };
  
  // 处理开始回复
  const handleStartReply = (commentId, replyToUser = null, isMainComment = true) => {
    setReplyTo(commentId);
    
    // 设置回复对象
    if (isMainComment) {
      // 回复主评论
      const comment = comments.find(c => c.id === commentId);
      if (comment) {
        setReplyToInfo({
          id: commentId,
          user: comment.author,
          isMainComment: true
        });
      }
    } else if (replyToUser) {
      // 回复某条回复
      setReplyToInfo({
        id: commentId,
        user: replyToUser,
        isMainComment: false
      });
    }
  };
  
  // 处理回复提交
  const handleReplySubmit = (commentId) => {
    if (replyText.trim()) {
      // 查找原评论
      const updatedComments = comments.map(comment => {
        if (comment.id === commentId) {
          // 如果评论没有回复数组，则创建
          const replies = comment.replies || [];
          // 添加新回复
          const newReply = {
            id: replies.length + 1,
            author: '当前用户',
            avatar: 'https://i.pravatar.cc/150?img=20',
            content: replyText,
            date: new Date().toLocaleString(),
            likes: 0,
            replyToUser: replyToInfo?.user || comment.author // 使用存储的回复对象信息
          };
          
          // 返回更新后的评论
          return {
            ...comment,
            replies: [...replies, newReply]
          };
        }
        return comment;
      });
      
      // 更新评论列表
      setComments(updatedComments);
      // 重置回复状态
      setReplyText('');
      setReplyTo(null);
      setReplyToInfo(null);
    }
  };
  
  // 处理取消回复
  const handleCancelReply = () => {
    setReplyTo(null);
    setReplyText('');
    setReplyToInfo(null);
  };
  
  // 处理评论文本框按键事件
  const handleCommentKeyDown = (e) => {
    // 仅在按下Shift+Enter时提交评论
    if (e.key === 'Enter' && e.shiftKey) {
      e.preventDefault();
      handleCommentSubmit();
    }
  };
  
  // 处理回复文本框按键事件
  const handleReplyKeyDown = (e, commentId) => {
    // 仅在按下Shift+Enter时提交回复
    if (e.key === 'Enter' && e.shiftKey) {
      e.preventDefault();
      handleReplySubmit(commentId);
    }
  };
  
  // 处理用户点击 - 导航到用户资料
  const navigateToUserProfile = (username) => {
    // 用户名作为查询参数传递给个人中心页面
    navigate(`/profile?user=${username}`);
  };
  
  // 处理关注/取消关注
  const handleFollowToggle = () => {
    setFollowing(!following);
    // 这里可以添加与后端交互的代码
  };
  
  if (!post) {
    return (
      <div className="App">
        <CssBaseline />
        <Navbar />
        <Container maxWidth="false" sx={{ mt: 3 }}>
          <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
            <Tabs 
              value={location.pathname}
              indicatorColor="primary"
              textColor="primary"
              variant="scrollable"
              scrollButtons="auto"
            >
              {navigationItems.map((item) => (
                <Tab
                  key={item.path}
                  label={item.label}
                  value={item.path}
                  component={Link}
                  to={item.path}
                  sx={{ 
                    minWidth: 100,
                    '&.Mui-selected': { fontWeight: 'bold' }
                  }}
                />
              ))}
            </Tabs>
          </Box>
        </Container>
        
        <Container maxWidth="false" sx={{ paddingTop: 3 }}>
          <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
            <Paper elevation={3} sx={{ p: 5, textAlign: 'center' }}>
              <Typography variant="h5">帖子不存在或已被删除</Typography>
              <Button 
                variant="contained" 
                component={Link} 
                to="/community" 
                sx={{ mt: 3 }}
              >
                返回社区
              </Button>
            </Paper>
          </Box>
        </Container>
      </div>
    );
  }
  
  return (
    <div className="App">
      <CssBaseline />
      <Navbar />
      
      <Container maxWidth="false" sx={{ mt: 3 }}>
        <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
          <Tabs 
            value={location.pathname.startsWith('/post') ? '/community' : location.pathname}
            indicatorColor="primary"
            textColor="primary"
            variant="scrollable"
            scrollButtons="auto"
          >
            {navigationItems.map((item) => (
              <Tab
                key={item.path}
                label={item.label}
                value={item.path}
                component={Link}
                to={item.path}
                sx={{ 
                  minWidth: 100,
                  '&.Mui-selected': { fontWeight: 'bold' }
                }}
              />
            ))}
          </Tabs>
        </Box>
      </Container>

      <Container maxWidth="false" sx={{ paddingTop: 3 }}>
        <Box sx={{ maxWidth: '1400px', mx: 'auto' }}>
          <Paper elevation={3} sx={{ p: 3, mb: 3 }}>
            {/* 帖子详情 */}
            <Box sx={{ mb: 4 }}>
              <Box sx={{ display: 'flex', alignItems: 'center', mb: 3 }}>
                <Tooltip title="查看用户资料">
                  <Avatar 
                    src={post.avatar} 
                    sx={{ 
                      width: 64, 
                      height: 64, 
                      mr: 2,
                      cursor: 'pointer',
                      '&:hover': { opacity: 0.8 }
                    }}
                    onClick={() => navigateToUserProfile(post.author)}
                  />
                </Tooltip>
                <Box sx={{ flex: 1 }}>
                  <Box sx={{ display: 'flex', alignItems: 'center' }}>
                    <Typography 
                      variant="subtitle1" 
                      sx={{ 
                        fontWeight: 'bold', 
                        fontSize: '1.1rem',
                        cursor: 'pointer',
                        '&:hover': { color: 'primary.main' }
                      }}
                      onClick={() => navigateToUserProfile(post.author)}
                    >
                      {post.author}
                    </Typography>
                    <Button
                      variant={following ? "outlined" : "contained"}
                      color="primary"
                      size="small"
                      startIcon={following ? <PersonRemoveIcon /> : <PersonAddIcon />}
                      onClick={handleFollowToggle}
                      sx={{ ml: 2, minWidth: 85 }}
                    >
                      {following ? '已关注' : '关注'}
                    </Button>
                  </Box>
                  <Typography variant="caption" color="text.secondary">
                    发布于 {post.date}
                  </Typography>
                </Box>
              </Box>
              
              <Typography variant="h4" gutterBottom sx={{ fontWeight: 'bold' }}>
                {post.title}
              </Typography>
              
              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 3 }}>
                <Box sx={{ display: 'flex', flexWrap: 'wrap', gap: 1 }}>
                  {post.tags.map((tag, index) => (
                    <Chip 
                      key={index} 
                      label={tag} 
                      size="small" 
                      color="primary"
                      variant="outlined"
                      sx={{ borderRadius: 1 }}
                    />
                  ))}
                </Box>
                <Button 
                  variant="outlined" 
                  size="small" 
                  component={Link} 
                  to="/community"
                  startIcon={<ArrowBackIcon />}
                >
                  返回社区
                </Button>
              </Box>
              
              <Typography variant="body1" paragraph sx={{ whiteSpace: 'pre-line', lineHeight: 1.8 }}>
                {post.content}
              </Typography>
              
              <Divider sx={{ my: 3 }} />
              
              {/* 交互按钮 */}
              <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                <Box sx={{ display: 'flex', gap: 2 }}>
                  <Button 
                    startIcon={<ThumbUpIcon />} 
                    onClick={handleLike}
                    color={liked ? "primary" : "inherit"}
                    variant={liked ? "contained" : "text"}
                  >
                    赞同 ({post.likes})
                  </Button>
                  <Button 
                    startIcon={<ChatBubbleOutlineIcon />}
                    onClick={scrollToCommentInput}
                  >
                    评论 ({comments.length})
                  </Button>
                </Box>
                <Box sx={{ display: 'flex', gap: 2 }}>
                  <IconButton>
                    <ShareIcon />
                  </IconButton>
                  <IconButton>
                    <BookmarkBorderIcon />
                  </IconButton>
                </Box>
              </Box>
            </Box>
            
            {/* 评论区 */}
            <Box>
              <Typography variant="h6" gutterBottom sx={{ fontWeight: 'bold', mb: 3 }}>
                全部评论 ({comments.length})
              </Typography>
              
              {/* 评论输入框 */}
              <Box sx={{ mb: 4 }}>
                <TextField
                  fullWidth
                  multiline
                  rows={3}
                  placeholder="写下你的评论..."
                  variant="outlined"
                  value={commentText}
                  onChange={(e) => setCommentText(e.target.value)}
                  onKeyDown={handleCommentKeyDown}
                  sx={{ mb: 2 }}
                  inputRef={commentInputRef}
                />
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Typography variant="caption" color="text.secondary">
                    按Enter键换行，按Shift+Enter键发送
                  </Typography>
                  <Button 
                    variant="contained" 
                    color="primary"
                    onClick={handleCommentSubmit}
                    disabled={!commentText.trim()}
                  >
                    发布评论
                  </Button>
                </Box>
              </Box>
              
              {/* 评论列表 */}
              <List>
                {comments.map((comment) => (
                  <React.Fragment key={comment.id}>
                    <ListItem alignItems="flex-start" sx={{ px: 0 }}>
                      <Box sx={{ display: 'flex', width: '100%' }}>
                        <Tooltip title="查看用户资料">
                          <Avatar 
                            src={comment.avatar} 
                            sx={{ 
                              mr: 2, 
                              cursor: 'pointer',
                              '&:hover': { opacity: 0.8 }
                            }}
                            onClick={() => navigateToUserProfile(comment.author)}
                          />
                        </Tooltip>
                        <Box sx={{ flex: 1 }}>
                          <Box sx={{ display: 'flex', justifyContent: 'space-between', mb: 1 }}>
                            <Typography 
                              variant="subtitle2" 
                              sx={{ 
                                fontWeight: 'bold',
                                cursor: 'pointer',
                                '&:hover': { color: 'primary.main' }
                              }}
                              onClick={() => navigateToUserProfile(comment.author)}
                            >
                              {comment.author}
                            </Typography>
                            <Typography variant="caption" color="text.secondary">
                              {comment.date}
                            </Typography>
                          </Box>
                          <Typography variant="body2" paragraph>
                            {comment.content}
                          </Typography>
                          <Box sx={{ display: 'flex', gap: 2 }}>
                            <Button 
                              size="small" 
                              startIcon={<ThumbUpIcon fontSize="small" />}
                              onClick={() => handleCommentLike(comment.id)}
                              color={likedComments[comment.id] ? "primary" : "inherit"}
                              variant={likedComments[comment.id] ? "contained" : "text"}
                            >
                              赞同 ({comment.likes})
                            </Button>
                            <Button 
                              size="small"
                              onClick={() => handleStartReply(comment.id)}
                            >
                              回复
                            </Button>
                          </Box>
                          
                          {/* 回复文本框 */}
                          {replyTo === comment.id && (
                            <Box sx={{ mt: 2, ml: 2 }}>
                              <TextField
                                fullWidth
                                multiline
                                rows={2}
                                placeholder={`回复 ${replyToInfo?.user || comment.author}...`}
                                variant="outlined"
                                value={replyText}
                                onChange={(e) => setReplyText(e.target.value)}
                                onKeyDown={(e) => handleReplyKeyDown(e, comment.id)}
                                sx={{ mb: 1 }}
                                autoFocus
                              />
                              <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                                <Typography variant="caption" color="text.secondary">
                                  按Enter键换行，按Shift+Enter键发送
                                </Typography>
                                <Box sx={{ display: 'flex', gap: 1 }}>
                                  <Button 
                                    variant="contained" 
                                    color="primary"
                                    size="small"
                                    onClick={() => handleReplySubmit(comment.id)}
                                    disabled={!replyText.trim()}
                                  >
                                    发送
                                  </Button>
                                  <Button 
                                    variant="outlined" 
                                    size="small"
                                    onClick={handleCancelReply}
                                  >
                                    取消
                                  </Button>
                                </Box>
                              </Box>
                            </Box>
                          )}
                          
                          {/* 显示回复列表 */}
                          {comment.replies && comment.replies.length > 0 && (
                            <Box sx={{ mt: 2, ml: 2 }}>
                              {comment.replies.map(reply => (
                                <Box key={reply.id} sx={{ mb: 2 }}>
                                  <Box sx={{ display: 'flex' }}>
                                    <Tooltip title="查看用户资料">
                                      <Avatar 
                                        src={reply.avatar} 
                                        sx={{ 
                                          width: 24, 
                                          height: 24, 
                                          mr: 1,
                                          cursor: 'pointer',
                                          '&:hover': { opacity: 0.8 }
                                        }}
                                        onClick={() => navigateToUserProfile(reply.author)}
                                      />
                                    </Tooltip>
                                    <Box>
                                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                                        <Typography 
                                          variant="subtitle2" 
                                          sx={{ 
                                            fontSize: '0.875rem',
                                            cursor: 'pointer',
                                            '&:hover': { color: 'primary.main' }
                                          }}
                                          onClick={() => navigateToUserProfile(reply.author)}
                                        >
                                          {reply.author}
                                        </Typography>
                                        <Typography variant="caption" color="text.secondary">
                                          回复
                                        </Typography>
                                        <Typography 
                                          variant="subtitle2" 
                                          sx={{ 
                                            fontSize: '0.875rem',
                                            cursor: 'pointer',
                                            '&:hover': { color: 'primary.main' }
                                          }}
                                          onClick={() => navigateToUserProfile(reply.replyToUser)}
                                        >
                                          {reply.replyToUser}
                                        </Typography>
                                      </Box>
                                      <Typography variant="body2" sx={{ mt: 0.5 }}>
                                        {reply.content}
                                      </Typography>
                                      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1, mt: 0.5 }}>
                                        <Typography variant="caption" color="text.secondary">
                                          {reply.date}
                                        </Typography>
                                        <Button 
                                          size="small" 
                                          sx={{ minWidth: 'auto', p: 0, fontSize: '0.75rem' }}
                                          onClick={() => handleStartReply(comment.id, reply.author, false)}
                                        >
                                          回复
                                        </Button>
                                      </Box>
                                    </Box>
                                  </Box>
                                </Box>
                              ))}
                            </Box>
                          )}
                        </Box>
                      </Box>
                    </ListItem>
                    <Divider component="li" sx={{ my: 2 }} />
                  </React.Fragment>
                ))}
              </List>
            </Box>
          </Paper>
          
          {/* 相关推荐 */}
          <Paper elevation={3} sx={{ p: 3 }}>
            <Typography variant="h6" gutterBottom sx={{ fontWeight: 'bold' }}>
              相关推荐
            </Typography>
            <Grid container spacing={3}>
              {posts
                .filter(p => p.id !== post.id)
                .slice(0, 2)
                .map(relatedPost => (
                  <Grid item xs={12} sm={6} key={relatedPost.id}>
                    <Card sx={{ height: '100%', transition: '0.3s', '&:hover': { boxShadow: 6 } }}>
                      <CardContent>
                        <Typography 
                          variant="h6" 
                          component={Link} 
                          to={`/post/${relatedPost.id}`}
                          onClick={() => {
                            // 页面已经在帖子详情页，强制刷新数据
                            window.scrollTo(0, 0); // 滚动到页面顶部
                          }}
                          sx={{ 
                            textDecoration: 'none',
                            color: 'inherit',
                            '&:hover': { color: 'primary.main' },
                            display: 'block',
                            mb: 1
                          }}
                        >
                          {relatedPost.title}
                        </Typography>
                        <Typography 
                          variant="body2" 
                          color="text.secondary"
                          sx={{
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            display: '-webkit-box',
                            WebkitLineClamp: 2,
                            WebkitBoxOrient: 'vertical',
                            mb: 2
                          }}
                        >
                          {relatedPost.content}
                        </Typography>
                        <Box sx={{ display: 'flex', justifyContent: 'space-between' }}>
                          <Typography variant="body2" color="text.secondary">
                            {relatedPost.author}
                          </Typography>
                          <Typography variant="body2" color="text.secondary">
                            👍 {relatedPost.likes} • 💬 {relatedPost.comments}
                          </Typography>
                        </Box>
                      </CardContent>
                    </Card>
                  </Grid>
                ))}
            </Grid>
          </Paper>
        </Box>
      </Container>
    </div>
  );
}

export default PostDetail; 